11 require_once( 'WatchedItem.php' );
12 require_once( 'Group.php' );
14 # Number of characters in user_token field
15 define( 'USER_TOKEN_LENGTH', 32 );
25 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
26 var $mEmailAuthenticated;
27 var $mRights, $mOptions;
28 var $mDataLoaded, $mNewpassword;
30 var $mBlockedby, $mBlockreason;
35 /** Array of group id the user belong to */
39 /** Construct using User:loadDefaults() */
41 $this->loadDefaults();
45 * Static factory method
46 * @param string $name Username, validated by Title:newFromText()
50 function newFromName( $name ) {
53 # Clean up name according to title rules
55 $t = Title
::newFromText( $name );
59 $u->setName( $t->getText() );
60 $u->setId( $u->idFromName( $t->getText() ) );
66 * Factory method to fetch whichever use has a given email confirmation code.
67 * This code is generated when an account is created or its e-mail address
70 * If the code is invalid or has expired, returns NULL.
76 function newFromConfirmationCode( $code ) {
77 $dbr =& wfGetDB( DB_SLAVE
);
78 $name = $dbr->selectField( 'user', 'user_name', array(
79 'user_email_token' => md5( $code ),
80 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
82 if( is_string( $name ) ) {
83 return User
::newFromName( $name );
90 * Get username given an id.
91 * @param integer $id Database user id
92 * @return string Nickname of a user
95 function whoIs( $id ) {
96 $dbr =& wfGetDB( DB_SLAVE
);
97 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
101 * Get real username given an id.
102 * @param integer $id Database user id
103 * @return string Realname of a user
106 function whoIsReal( $id ) {
107 $dbr =& wfGetDB( DB_SLAVE
);
108 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
112 * Get database id given a user name
113 * @param string $name Nickname of a user
114 * @return integer|null Database user id (null: if non existent
117 function idFromName( $name ) {
118 $fname = "User::idFromName";
120 $nt = Title
::newFromText( $name );
121 if( is_null( $nt ) ) {
125 $dbr =& wfGetDB( DB_SLAVE
);
126 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
128 if ( $s === false ) {
136 * does the string match an anonymous IPv4 address?
139 * @param string $name Nickname of a user
142 function isIP( $name ) {
143 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
144 /*return preg_match("/^
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
146 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
147 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
148 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
153 * does the string match roughly an email address ?
157 * @param string $addr email address
161 function isValidEmailAddr ( $addr ) {
162 # There used to be a regular expression here, it got removed because it
163 # rejected valid addresses.
164 return ( trim( $addr ) != '' ) &&
165 (false !== strpos( $addr, '@' ) );
169 * probably return a random password
170 * @return string probably a random password
172 * @todo Check what is doing really [AV]
174 function randomPassword() {
175 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
176 $l = strlen( $pwchars ) - 1;
178 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
179 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
180 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
181 $pwchars{mt_rand( 0, $l )};
186 * Set properties to default
187 * Used at construction. It will load per language default settings only
188 * if we have an available language object.
190 function loadDefaults() {
193 $fname = 'User::loadDefaults' . $n;
194 wfProfileIn( $fname );
196 global $wgContLang, $wgIP, $wgDBname;
197 global $wgNamespacesToBeSearchedDefault;
200 $this->mNewtalk
= -1;
201 $this->mName
= $wgIP;
202 $this->mRealName
= $this->mEmail
= '';
203 $this->mEmailAuthenticated
= null;
204 $this->mPassword
= $this->mNewpassword
= '';
205 $this->mRights
= array();
206 $this->mGroups
= array();
207 // Getting user defaults only if we have an available language
208 if( isset( $wgContLang ) ) {
209 $this->loadDefaultFromLanguage();
212 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
213 $this->mOptions
['searchNs'.$nsnum] = $val;
215 unset( $this->mSkin
);
216 $this->mDataLoaded
= false;
217 $this->mBlockedby
= -1; # Unset
218 $this->setToken(); # Random
219 $this->mHash
= false;
221 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
222 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
225 $this->mTouched
= '0'; # Allow any pages to be cached
228 wfProfileOut( $fname );
232 * Used to load user options from a language.
233 * This is not in loadDefault() cause we sometime create user before having
236 function loadDefaultFromLanguage(){
237 $this->mOptions
= User
::getDefaultOptions();
241 * Combine the language default options with any site-specific options
242 * and add the default language variants.
248 function getDefaultOptions() {
250 * Site defaults will override the global/language defaults
252 global $wgContLang, $wgDefaultUserOptions;
253 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
256 * default language setting
258 $variant = $wgContLang->getPreferredVariant();
259 $defOpt['variant'] = $variant;
260 $defOpt['language'] = $variant;
266 * Get a given default option value.
273 function getDefaultOption( $opt ) {
274 $defOpts = User
::getDefaultOptions();
275 if( isset( $defOpts[$opt] ) ) {
276 return $defOpts[$opt];
283 * Get blocking information
285 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
286 * non-critical checks are done against slaves. Check when actually saving should be done against
289 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
290 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
291 * just slightly outta sync and soon corrected - safer to block slightly more that less.
292 * And it's cheaper to check slave first, then master if needed, than master always.
294 function getBlockedStatus( $bFromSlave = true ) {
295 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
297 if ( -1 != $this->mBlockedby
) { return; }
299 $this->mBlockedby
= 0;
303 $block = new Block();
304 $block->forUpdate( $bFromSlave );
305 if ( $block->load( $wgIP , $this->mId
) ) {
306 $this->mBlockedby
= $block->mBy
;
307 $this->mBlockreason
= $block->mReason
;
308 $this->spreadBlock();
313 if ( !$this->mBlockedby
) {
314 # Check first against slave, and optionally from master.
315 $block = $wgBlockCache->get( $wgIP, true );
316 if ( !$block && !$bFromSlave )
318 # Not blocked: check against master, to make sure.
319 $wgBlockCache->clearLocal( );
320 $block = $wgBlockCache->get( $wgIP, false );
322 if ( $block !== false ) {
323 $this->mBlockedby
= $block->mBy
;
324 $this->mBlockreason
= $block->mReason
;
329 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
332 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
333 $this->mBlockedby
= wfMsg( 'proxyblocker' );
334 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
338 if ( !$this->mBlockedby
&& $wgEnableSorbs ) {
339 if ( $this->inSorbsBlacklist( $wgIP ) ) {
340 $this->mBlockedby
= wfMsg( 'sorbs' );
341 $this->mBlockreason
= wfMsg( 'sorbsreason' );
347 function inSorbsBlacklist( $ip ) {
348 global $wgEnableSorbs;
349 return $wgEnableSorbs &&
350 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
353 function inOpmBlacklist( $ip ) {
355 return $wgEnableOpm &&
356 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
359 function inDnsBlacklist( $ip, $base ) {
360 $fname = 'User::inDnsBlacklist';
361 wfProfileIn( $fname );
366 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
368 for ( $i=4; $i>=1; $i-- ) {
369 $host .= $m[$i] . '.';
374 $ipList = gethostbynamel( $host );
377 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
380 wfDebug( "Requested $host, not found in $base.\n" );
384 wfProfileOut( $fname );
389 * Primitive rate limits: enforce maximum actions per time period
390 * to put a brake on flooding.
392 * Note: when using a shared cache like memcached, IP-address
393 * last-hit counters will be shared across wikis.
395 * @return bool true if a rate limiter was tripped
398 function pingLimiter( $action='edit' ) {
399 global $wgRateLimits;
400 if( !isset( $wgRateLimits[$action] ) ) {
403 if( $this->isAllowed( 'delete' ) ) {
408 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
409 $fname = 'User::pingLimiter';
410 $limits = $wgRateLimits[$action];
412 $id = $this->getId();
414 if( isset( $limits['anon'] ) && $id == 0 ) {
415 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
418 if( isset( $limits['user'] ) && $id != 0 ) {
419 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
421 if( $this->isNewbie() ) {
422 if( isset( $limits['newbie'] ) && $id != 0 ) {
423 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
425 if( isset( $limits['ip'] ) ) {
426 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
428 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
429 $subnet = $matches[1];
430 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
435 foreach( $keys as $key => $limit ) {
436 list( $max, $period ) = $limit;
437 $summary = "(limit $max in {$period}s)";
438 $count = $wgMemc->get( $key );
440 if( $count > $max ) {
441 wfDebug( "$fname: tripped! $key at $count $summary\n" );
442 if( $wgRateLimitLog ) {
443 @error_log
( wfTimestamp( TS_MW
) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
447 wfDebug( "$fname: ok. $key at $count $summary\n" );
450 wfDebug( "$fname: adding record for $key $summary\n" );
451 $wgMemc->add( $key, 1, IntVal( $period ) );
453 $wgMemc->incr( $key );
460 * Check if user is blocked
461 * @return bool True if blocked, false otherwise
463 function isBlocked( $bFromSlave = false ) {
464 $this->getBlockedStatus( $bFromSlave );
465 return $this->mBlockedby
!== 0;
469 * Get name of blocker
470 * @return string name of blocker
472 function blockedBy() {
473 $this->getBlockedStatus();
474 return $this->mBlockedby
;
478 * Get blocking reason
479 * @return string Blocking reason
481 function blockedFor() {
482 $this->getBlockedStatus();
483 return $this->mBlockreason
;
487 * Initialise php session
489 function SetupSession() {
490 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
491 if( $wgSessionsInMemcached ) {
492 require_once( 'MemcachedSessions.php' );
493 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
494 # If it's left on 'user' or another setting from another
495 # application, it will end up failing. Try to recover.
496 ini_set ( 'session.save_handler', 'files' );
498 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
499 session_cache_limiter( 'private, must-revalidate' );
504 * Read datas from session
507 function loadFromSession() {
508 global $wgMemc, $wgDBname;
510 if ( isset( $_SESSION['wsUserID'] ) ) {
511 if ( 0 != $_SESSION['wsUserID'] ) {
512 $sId = $_SESSION['wsUserID'];
516 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
517 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
518 $_SESSION['wsUserID'] = $sId;
522 if ( isset( $_SESSION['wsUserName'] ) ) {
523 $sName = $_SESSION['wsUserName'];
524 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
525 $sName = $_COOKIE["{$wgDBname}UserName"];
526 $_SESSION['wsUserName'] = $sName;
531 $passwordCorrect = FALSE;
532 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
533 if($makenew = !$user) {
534 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
537 $user->loadFromDatabase();
539 wfDebug( "User::loadFromSession() got from cache!\n" );
542 if ( isset( $_SESSION['wsToken'] ) ) {
543 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
544 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
545 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
547 return new User(); # Can't log in from session
550 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
552 if($wgMemc->set( $key, $user ))
553 wfDebug( "User::loadFromSession() successfully saved user\n" );
555 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
559 return new User(); # Can't log in from session
563 * Load a user from the database
565 function loadFromDatabase() {
566 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
567 $fname = "User::loadFromDatabase";
569 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
570 # loading in a command line script, don't assume all command line scripts need it like this
571 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
572 if ( $this->mDataLoaded
) {
577 $this->mId
= IntVal( $this->mId
);
579 /** Anonymous user */
582 $anong = Group
::newFromId($wgAnonGroupId);
584 wfDebugDieBacktrace("Please update your database schema "
585 ."and populate initial group data from "
586 ."maintenance/archives patches");
587 $anong->loadFromDatabase();
588 $this->mRights
= explode(',', $anong->getRights());
589 $this->mDataLoaded
= true;
591 } # the following stuff is for non-anonymous users only
593 $dbr =& wfGetDB( DB_SLAVE
);
594 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
595 'user_email_authenticated',
596 'user_real_name','user_options','user_touched', 'user_token' ),
597 array( 'user_id' => $this->mId
), $fname );
599 if ( $s !== false ) {
600 $this->mName
= $s->user_name
;
601 $this->mEmail
= $s->user_email
;
602 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
603 $this->mRealName
= $s->user_real_name
;
604 $this->mPassword
= $s->user_password
;
605 $this->mNewpassword
= $s->user_newpassword
;
606 $this->decodeOptions( $s->user_options
);
607 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
608 $this->mToken
= $s->user_token
;
611 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId
) );
613 // add the default group for logged in user
614 $this->mGroups
= array( $wgLoggedInGroupId );
616 while($group = $dbr->fetchRow($res)) {
617 if ( $group[0] != $wgLoggedInGroupId ) {
618 $this->mGroups
[] = $group[0];
623 $this->mRights
= array();
624 // now we merge groups rights to get this user rights
625 foreach($this->mGroups
as $aGroupId) {
626 $g = Group
::newFromId($aGroupId);
627 $g->loadFromDatabase();
628 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
631 // array merge duplicate rights which are part of several groups
632 $this->mRights
= array_unique($this->mRights
);
634 $dbr->freeResult($res);
637 $this->mDataLoaded
= true;
640 function getID() { return $this->mId
; }
641 function setID( $v ) {
643 $this->mDataLoaded
= false;
647 $this->loadFromDatabase();
651 function setName( $str ) {
652 $this->loadFromDatabase();
658 * Return the title dbkey form of the name, for eg user pages.
662 function getTitleKey() {
663 return str_replace( ' ', '_', $this->getName() );
666 function getNewtalk() {
667 $fname = 'User::getNewtalk';
668 $this->loadFromDatabase();
670 # Load the newtalk status if it is unloaded (mNewtalk=-1)
671 if( $this->mNewtalk
== -1 ) {
672 $this->mNewtalk
= 0; # reset talk page status
674 # Check memcached separately for anons, who have no
675 # entire User object stored in there.
677 global $wgDBname, $wgMemc;
678 $key = "$wgDBname:newtalk:ip:{$this->mName}";
679 $newtalk = $wgMemc->get( $key );
680 if( is_integer( $newtalk ) ) {
681 $this->mNewtalk
= $newtalk ?
1 : 0;
682 return (bool)$this->mNewtalk
;
686 $dbr =& wfGetDB( DB_SLAVE
);
687 $res = $dbr->select( 'watchlist',
689 array( 'wl_title' => $this->getTitleKey(),
690 'wl_namespace' => NS_USER_TALK
,
691 'wl_user' => $this->mId
,
692 'wl_notificationtimestamp != 0' ),
693 'User::getNewtalk' );
694 if( $dbr->numRows($res) > 0 ) {
697 $dbr->freeResult( $res );
700 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
704 return ( 0 != $this->mNewtalk
);
707 function setNewtalk( $val ) {
708 $this->loadFromDatabase();
709 $this->mNewtalk
= $val;
710 $this->invalidateCache();
713 function invalidateCache() {
714 $this->loadFromDatabase();
715 $this->mTouched
= wfTimestampNow();
716 # Don't forget to save the options after this or
717 # it won't take effect!
720 function validateCache( $timestamp ) {
721 $this->loadFromDatabase();
722 return ($timestamp >= $this->mTouched
);
727 * Will only be salted if $wgPasswordSalt is true
728 * @param string Password.
729 * @return string Salted password or clear password.
731 function addSalt( $p ) {
732 global $wgPasswordSalt;
734 return md5( "{$this->mId}-{$p}" );
740 * Encrypt a password.
741 * It can eventuall salt a password @see User::addSalt()
742 * @param string $p clear Password.
743 * @param string Encrypted password.
745 function encryptPassword( $p ) {
746 return $this->addSalt( md5( $p ) );
749 # Set the password and reset the random token
750 function setPassword( $str ) {
751 $this->loadFromDatabase();
753 $this->mPassword
= $this->encryptPassword( $str );
754 $this->mNewpassword
= '';
757 # Set the random token (used for persistent authentication)
758 function setToken( $token = false ) {
759 global $wgSecretKey, $wgProxyKey, $wgDBname;
761 if ( $wgSecretKey ) {
763 } elseif ( $wgProxyKey ) {
768 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
770 $this->mToken
= $token;
775 function setCookiePassword( $str ) {
776 $this->loadFromDatabase();
777 $this->mCookiePassword
= md5( $str );
780 function setNewpassword( $str ) {
781 $this->loadFromDatabase();
782 $this->mNewpassword
= $this->encryptPassword( $str );
785 function getEmail() {
786 $this->loadFromDatabase();
787 return $this->mEmail
;
790 function getEmailAuthenticationTimestamp() {
791 $this->loadFromDatabase();
792 return $this->mEmailAuthenticated
;
795 function setEmail( $str ) {
796 $this->loadFromDatabase();
797 $this->mEmail
= $str;
800 function getRealName() {
801 $this->loadFromDatabase();
802 return $this->mRealName
;
805 function setRealName( $str ) {
806 $this->loadFromDatabase();
807 $this->mRealName
= $str;
810 function getOption( $oname ) {
811 $this->loadFromDatabase();
812 if ( array_key_exists( $oname, $this->mOptions
) ) {
813 return $this->mOptions
[$oname];
819 function setOption( $oname, $val ) {
820 $this->loadFromDatabase();
821 if ( $oname == 'skin' ) {
822 # Clear cached skin, so the new one displays immediately in Special:Preferences
823 unset( $this->mSkin
);
825 $this->mOptions
[$oname] = $val;
826 $this->invalidateCache();
829 function getRights() {
830 $this->loadFromDatabase();
831 return $this->mRights
;
834 function addRight( $rname ) {
835 $this->loadFromDatabase();
836 array_push( $this->mRights
, $rname );
837 $this->invalidateCache();
840 function getGroups() {
841 $this->loadFromDatabase();
842 return $this->mGroups
;
845 function setGroups($groups) {
846 $this->loadFromDatabase();
847 $this->mGroups
= $groups;
848 $this->invalidateCache();
852 * A more legible check for non-anonymousness.
853 * Returns true if the user is not an anonymous visitor.
857 function isLoggedIn() {
858 return( $this->getID() != 0 );
862 * A more legible check for anonymousness.
863 * Returns true if the user is an anonymous visitor.
868 return !$this->isLoggedIn();
872 * Check if a user is sysop
873 * Die with backtrace. Use User:isAllowed() instead.
877 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
881 function isDeveloper() {
882 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
886 function isBureaucrat() {
887 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
891 * Whether the user is a bot
892 * @todo need to be migrated to the new user level management sytem
895 $this->loadFromDatabase();
896 return in_array( 'bot', $this->mRights
);
900 * Check if user is allowed to access a feature / make an action
901 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
902 * @return boolean True: action is allowed, False: action should not be allowed
904 function isAllowed($action='') {
905 $this->loadFromDatabase();
906 return in_array( $action , $this->mRights
);
910 * Load a skin if it doesn't exist or return it
911 * @todo FIXME : need to check the old failback system [AV]
913 function &getSkin() {
915 if ( ! isset( $this->mSkin
) ) {
916 $fname = 'User::getSkin';
917 wfProfileIn( $fname );
919 # get all skin names available
920 $skinNames = Skin
::getSkinNames();
923 $userSkin = $this->getOption( 'skin' );
924 if ( $userSkin == '' ) { $userSkin = 'standard'; }
926 if ( !isset( $skinNames[$userSkin] ) ) {
927 # in case the user skin could not be found find a replacement
932 # if phptal is enabled we should have monobook skin that
933 # superseed the good old SkinStandard.
934 if ( isset( $skinNames['monobook'] ) ) {
935 $fallback[0] = 'MonoBook';
938 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
939 $sn = $fallback[$userSkin];
944 # The user skin is available
945 $sn = $skinNames[$userSkin];
948 # Grab the skin class and initialise it. Each skin checks for PHPTal
949 # and will not load if it's not enabled.
950 require_once( $IP.'/skins/'.$sn.'.php' );
952 # Check if we got if not failback to default skin
953 $className = 'Skin'.$sn;
954 if( !class_exists( $className ) ) {
955 # DO NOT die if the class isn't found. This breaks maintenance
956 # scripts and can cause a user account to be unrecoverable
957 # except by SQL manipulation if a previously valid skin name
958 # is no longer valid.
959 $className = 'SkinStandard';
960 require_once( $IP.'/skins/Standard.php' );
962 $this->mSkin
=& new $className;
963 wfProfileOut( $fname );
969 * @param string $title Article title to look at
973 * Check watched status of an article
974 * @return bool True if article is watched
976 function isWatched( $title ) {
977 $wl = WatchedItem
::fromUserTitle( $this, $title );
978 return $wl->isWatched();
984 function addWatch( $title ) {
985 $wl = WatchedItem
::fromUserTitle( $this, $title );
987 $this->invalidateCache();
991 * Stop watching an article
993 function removeWatch( $title ) {
994 $wl = WatchedItem
::fromUserTitle( $this, $title );
996 $this->invalidateCache();
1000 * Clear the user's notification timestamp for the given title.
1001 * If e-notif e-mails are on, they will receive notification mails on
1002 * the next change of the page if it's watched etc.
1004 function clearNotification( &$title ) {
1007 $userid = $this->getID();
1011 // Only update the timestamp if the page is being watched.
1012 // The query to find out if it is watched is cached both in memcached and per-invocation,
1013 // and when it does have to be executed, it can be on a slave
1014 // If this is the user's newtalk page, we always update the timestamp
1015 if ($title->getNamespace() == NS_USER_TALK
&&
1016 $title->getText() == $wgUser->getName())
1019 } elseif ( $this->getID() == $wgUser->getID() ) {
1020 $watched = $title->userIsWatching();
1025 // If the page is watched by the user (or may be watched), update the timestamp on any
1026 // any matching rows
1028 $dbw =& wfGetDB( DB_MASTER
);
1029 $success = $dbw->update( 'watchlist',
1031 'wl_notificationtimestamp' => 0
1032 ), array( /* WHERE */
1033 'wl_title' => $title->getDBkey(),
1034 'wl_namespace' => $title->getNamespace(),
1035 'wl_user' => $this->getID()
1036 ), 'User::clearLastVisited'
1044 * Resets all of the given user's page-change notification timestamps.
1045 * If e-notif e-mails are on, they will receive notification mails on
1046 * the next change of any watched page.
1048 * @param int $currentUser user ID number
1051 function clearAllNotifications( $currentUser ) {
1052 if( $currentUser != 0 ) {
1054 $dbw =& wfGetDB( DB_MASTER
);
1055 $success = $dbw->update( 'watchlist',
1057 'wl_notificationtimestamp' => 0
1058 ), array( /* WHERE */
1059 'wl_user' => $currentUser
1060 ), 'UserMailer::clearAll'
1063 # we also need to clear here the "you have new message" notification for the own user_talk page
1064 # This is cleared one page view later in Article::viewUpdates();
1070 * @return string Encoding options
1072 function encodeOptions() {
1074 foreach ( $this->mOptions
as $oname => $oval ) {
1075 array_push( $a, $oname.'='.$oval );
1077 $s = implode( "\n", $a );
1084 function decodeOptions( $str ) {
1085 $a = explode( "\n", $str );
1086 foreach ( $a as $s ) {
1087 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1088 $this->mOptions
[$m[1]] = $m[2];
1093 function setCookies() {
1094 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1095 if ( 0 == $this->mId
) return;
1096 $this->loadFromDatabase();
1097 $exp = time() +
$wgCookieExpiration;
1099 $_SESSION['wsUserID'] = $this->mId
;
1100 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
1102 $_SESSION['wsUserName'] = $this->mName
;
1103 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1105 $_SESSION['wsToken'] = $this->mToken
;
1106 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1107 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1109 setcookie( $wgDBname.'Token', '', time() - 3600 );
1115 * It will clean the session cookie
1118 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1119 $this->loadDefaults();
1120 $this->setLoaded( true );
1122 $_SESSION['wsUserID'] = 0;
1124 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1125 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1127 # Remember when user logged out, to prevent seeing cached pages
1128 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1132 * Save object settings into database
1134 function saveSettings() {
1135 global $wgMemc, $wgDBname;
1136 $fname = 'User::saveSettings';
1138 $dbw =& wfGetDB( DB_MASTER
);
1139 if ( ! $this->getNewtalk() ) {
1140 # Delete the watchlist entry for user_talk page X watched by user X
1141 $dbw->delete( 'watchlist',
1142 array( 'wl_user' => $this->mId
,
1143 'wl_title' => $this->getTitleKey(),
1144 'wl_namespace' => NS_USER_TALK
),
1147 # Anon users have a separate memcache space for newtalk
1148 # since they don't store their own info. Trim...
1149 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1153 if ( 0 == $this->mId
) { return; }
1155 $dbw->update( 'user',
1157 'user_name' => $this->mName
,
1158 'user_password' => $this->mPassword
,
1159 'user_newpassword' => $this->mNewpassword
,
1160 'user_real_name' => $this->mRealName
,
1161 'user_email' => $this->mEmail
,
1162 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1163 'user_options' => $this->encodeOptions(),
1164 'user_touched' => $dbw->timestamp($this->mTouched
),
1165 'user_token' => $this->mToken
1166 ), array( /* WHERE */
1167 'user_id' => $this->mId
1170 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
1171 'ur_user='. $this->mId
, $fname );
1172 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1174 // delete old groups
1175 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
1178 foreach ($this->mGroups
as $group) {
1179 $dbw->replace( 'user_groups',
1180 array(array('ug_user','ug_group')),
1182 'ug_user' => $this->mId
,
1183 'ug_group' => $group
1191 * Checks if a user with the given name exists, returns the ID
1193 function idForName() {
1194 $fname = 'User::idForName';
1197 $s = trim( $this->mName
);
1198 if ( 0 == strcmp( '', $s ) ) return 0;
1200 $dbr =& wfGetDB( DB_SLAVE
);
1201 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1202 if ( $id === false ) {
1209 * Add user object to the database
1211 function addToDatabase() {
1212 $fname = 'User::addToDatabase';
1213 $dbw =& wfGetDB( DB_MASTER
);
1214 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1215 $dbw->insert( 'user',
1217 'user_id' => $seqVal,
1218 'user_name' => $this->mName
,
1219 'user_password' => $this->mPassword
,
1220 'user_newpassword' => $this->mNewpassword
,
1221 'user_email' => $this->mEmail
,
1222 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1223 'user_real_name' => $this->mRealName
,
1224 'user_options' => $this->encodeOptions(),
1225 'user_token' => $this->mToken
1228 $this->mId
= $dbw->insertId();
1229 $dbw->insert( 'user_rights',
1231 'ur_user' => $this->mId
,
1232 'ur_rights' => implode( ',', $this->mRights
)
1236 foreach ($this->mGroups
as $group) {
1237 $dbw->insert( 'user_groups',
1239 'ug_user' => $this->mId
,
1240 'ug_group' => $group
1246 function spreadBlock() {
1248 # If the (non-anonymous) user is blocked, this function will block any IP address
1249 # that they successfully log on from.
1250 $fname = 'User::spreadBlock';
1252 wfDebug( "User:spreadBlock()\n" );
1253 if ( $this->mId
== 0 ) {
1257 $userblock = Block
::newFromDB( '', $this->mId
);
1258 if ( !$userblock->isValid() ) {
1262 # Check if this IP address is already blocked
1263 $ipblock = Block
::newFromDB( $wgIP );
1264 if ( $ipblock->isValid() ) {
1265 # Just update the timestamp
1266 $ipblock->updateTimestamp();
1270 # Make a new block object with the desired properties
1271 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1272 $ipblock->mAddress
= $wgIP;
1273 $ipblock->mUser
= 0;
1274 $ipblock->mBy
= $userblock->mBy
;
1275 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1276 $ipblock->mTimestamp
= wfTimestampNow();
1277 $ipblock->mAuto
= 1;
1278 # If the user is already blocked with an expiry date, we don't
1279 # want to pile on top of that!
1280 if($userblock->mExpiry
) {
1281 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1283 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1291 function getPageRenderingHash() {
1294 return $this->mHash
;
1297 // stubthreshold is only included below for completeness,
1298 // it will always be 0 when this function is called by parsercache.
1300 $confstr = $this->getOption( 'math' );
1301 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1302 $confstr .= '!' . $this->getOption( 'editsection' );
1303 $confstr .= '!' . $this->getOption( 'date' );
1304 $confstr .= '!' . $this->getOption( 'numberheadings' );
1305 $confstr .= '!' . $this->getOption( 'language' );
1306 $confstr .= '!' . $this->getOption( 'thumbsize' );
1307 // add in language specific options, if any
1308 $extra = $wgContLang->getExtraHashOptions();
1311 $this->mHash
= $confstr;
1315 function isAllowedToCreateAccount() {
1316 global $wgWhitelistAccount;
1319 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1320 foreach ($wgWhitelistAccount as $right => $ok) {
1321 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1322 $allowed |
= ($ok && $userHasRight);
1328 * Set mDataLoaded, return previous value
1329 * Use this to prevent DB access in command-line scripts or similar situations
1331 function setLoaded( $loaded ) {
1332 return wfSetVar( $this->mDataLoaded
, $loaded );
1336 * Get this user's personal page title.
1341 function getUserPage() {
1342 return Title
::makeTitle( NS_USER
, $this->mName
);
1346 * Get this user's talk page title.
1351 function getTalkPage() {
1352 $title = $this->getUserPage();
1353 return $title->getTalkPage();
1359 function getMaxID() {
1360 $dbr =& wfGetDB( DB_SLAVE
);
1361 return $dbr->selectField( 'user', 'max(user_id)', false );
1365 * Determine whether the user is a newbie. Newbies are either
1366 * anonymous IPs, or the 1% most recently created accounts.
1367 * Bots and sysops are excluded.
1368 * @return bool True if it is a newbie.
1370 function isNewbie() {
1371 return $this->isAnon() ||
$this->mId
> User
::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1375 * Check to see if the given clear-text password is one of the accepted passwords
1376 * @param string $password User password.
1377 * @return bool True if the given password is correct otherwise False.
1379 function checkPassword( $password ) {
1381 $this->loadFromDatabase();
1383 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1385 } elseif( $wgAuth->strict() ) {
1386 /* Auth plugin doesn't allow local authentication */
1389 $ep = $this->encryptPassword( $password );
1390 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1392 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1394 } elseif ( function_exists( 'iconv' ) ) {
1395 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1396 # Check for this with iconv
1397 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1398 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1406 * Initialize (if necessary) and return a session token value
1407 * which can be used in edit forms to show that the user's
1408 * login credentials aren't being hijacked with a foreign form
1411 * @param mixed $salt - Optional function-specific data for hash.
1412 * Use a string or an array of strings.
1416 function editToken( $salt = '' ) {
1417 if( !isset( $_SESSION['wsEditToken'] ) ) {
1418 $token = $this->generateToken();
1419 $_SESSION['wsEditToken'] = $token;
1421 $token = $_SESSION['wsEditToken'];
1423 if( is_array( $salt ) ) {
1424 $salt = implode( '|', $salt );
1426 return md5( $token . $salt );
1430 * Generate a hex-y looking random token for various uses.
1431 * Could be made more cryptographically sure if someone cares.
1434 function generateToken( $salt = '' ) {
1435 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1436 return md5( $token . $salt );
1440 * Check given value against the token value stored in the session.
1441 * A match should confirm that the form was submitted from the
1442 * user's own login session, not a form submission from a third-party
1445 * @param string $val - the input value to compare
1446 * @param string $salt - Optional function-specific data for hash
1450 function matchEditToken( $val, $salt = '' ) {
1451 return ( $val == $this->editToken( $salt ) );
1455 * Generate a new e-mail confirmation token and send a confirmation
1456 * mail to the user's given address.
1458 * @return mixed True on success, a WikiError object on failure.
1460 function sendConfirmationMail() {
1461 global $wgIP, $wgContLang;
1462 $url = $this->confirmationTokenUrl( $expiration );
1463 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1464 wfMsg( 'confirmemail_body',
1468 $wgContLang->timeanddate( $expiration, false ) ) );
1472 * Send an e-mail to this user's account. Does not check for
1473 * confirmed status or validity.
1475 * @param string $subject
1476 * @param string $body
1477 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1478 * @return mixed True on success, a WikiError object on failure.
1480 function sendMail( $subject, $body, $from = null ) {
1481 if( is_null( $from ) ) {
1482 global $wgPasswordSender;
1483 $from = $wgPasswordSender;
1486 require_once( 'UserMailer.php' );
1487 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1489 if( $error == '' ) {
1492 return new WikiError( $error );
1497 * Generate, store, and return a new e-mail confirmation code.
1498 * A hash (unsalted since it's used as a key) is stored.
1499 * @param &$expiration mixed output: accepts the expiration time
1503 function confirmationToken( &$expiration ) {
1504 $fname = 'User::confirmationToken';
1507 $expires = $now +
7 * 24 * 60 * 60;
1508 $expiration = wfTimestamp( TS_MW
, $expires );
1510 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1511 $hash = md5( $token );
1513 $dbw =& wfGetDB( DB_MASTER
);
1514 $dbw->update( 'user',
1515 array( 'user_email_token' => $hash,
1516 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1517 array( 'user_id' => $this->mId
),
1524 * Generate and store a new e-mail confirmation token, and return
1525 * the URL the user can use to confirm.
1526 * @param &$expiration mixed output: accepts the expiration time
1530 function confirmationTokenUrl( &$expiration ) {
1531 $token = $this->confirmationToken( $expiration );
1532 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1533 return $title->getFullUrl();
1537 * Mark the e-mail address confirmed and save.
1539 function confirmEmail() {
1540 $this->loadFromDatabase();
1541 $this->mEmailAuthenticated
= wfTimestampNow();
1542 $this->saveSettings();
1547 * Is this user allowed to send e-mails within limits of current
1548 * site configuration?
1551 function canSendEmail() {
1552 return $this->isEmailConfirmed();
1556 * Is this user allowed to receive e-mails within limits of current
1557 * site configuration?
1560 function canReceiveEmail() {
1561 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1565 * Is this user's e-mail address valid-looking and confirmed within
1566 * limits of the current site configuration?
1568 * If $wgEmailAuthentication is on, this may require the user to have
1569 * confirmed their address by returning a code or using a password
1570 * sent to the address from the wiki.
1574 function isEmailConfirmed() {
1575 global $wgEmailAuthentication;
1576 $this->loadFromDatabase();
1577 if( $this->isAnon() )
1579 if( !$this->isValidEmailAddr( $this->mEmail
) )
1581 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )